import { resolve } from "path"
import { gitDir } from "./git/git-dir"
import { getJSON } from "./lib/base/get-json"
import { writeFileSync } from "fs"
import eol from "eol"

export interface GitlabProject {
  path: string
  projectId: string
}

export type ConfigJSON = {
  base: {
    [x: string]: string
  }
  branches: {
    [x: string]: string
  }
  createdTime: {
    [x: string]: string
  }
  projectInfo: GitlabProject
  excludes: string[]
  mergingBranch?: string
  prefix?: string // 提交前缀
  submodules?: string[] // 子模块的文件夹路径
}


const defaultFilePath = resolve(gitDir(), '.idea/config.json')
const configFilePath = defaultFilePath

const defaultConfigJSON: ConfigJSON = {
  projectInfo: { projectId: '', path: '' },
  base: {},
  branches: {},
  createdTime: {},
  excludes: [],
  submodules: [],
}
const DEFAULT_TRANSFORM = [
  [/.*\/refs#/, 'refs #'],
  ['refs#', 'refs #'],
  ['-', ' '],
  ['feature/', ''],
]

export const config = getJSON<ConfigJSON>(configFilePath, defaultConfigJSON) as ConfigJSON
export function saveConfigJSON() {
  writeFileSync(configFilePath, eol.auto(JSON.stringify(config, null, 2)))
}
export function applyTransform(message: string, defaultTransform  = DEFAULT_TRANSFORM) {
  const transform = defaultTransform
  if (transform) {
    for (const [key, value] of transform) {
      message = message.replace(key, String(value))
    }
  }
  return message
}